package cn.findviewbydream.evil.main.service.impl;

import cn.findviewbydream.evil.main.dao.ReleaseNewpostDao;
import cn.findviewbydream.evil.main.dto.CodeTypeBean;
import cn.findviewbydream.evil.main.entity.CodeTypeEntity;
import cn.findviewbydream.evil.main.entity.PostEntity;
import cn.findviewbydream.evil.main.entity.UserEntity;
import cn.findviewbydream.evil.main.enums.ReleaseNewpostType;
import cn.findviewbydream.evil.main.service.ReleaseNewpostService;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/********************************************
 * 工程名：HebeuCS
 * 包名：cn.findviewbydream.evil.main.service.impl
 * 时间：16-11-14
 * 作者：白雨濃 evil
 * 邮箱：evilbai@foxmail.com
 * 内容：发布新贴实现类
 ********************************************/
@Service("releaseNewpostService")
public class ReleaseNewpostServiceImpl implements ReleaseNewpostService
{
    private Logger logger = LoggerFactory.getLogger(ReleaseNewpostServiceImpl.class);

    private static final int RELEASELIMIT = 1;/*发布文章时间限制，默认10min*/

    private final ReleaseNewpostDao releaseNewpostDao;

    @Autowired
    public ReleaseNewpostServiceImpl(ReleaseNewpostDao releaseNewpostDao) {this.releaseNewpostDao = releaseNewpostDao;}


    @Override
    public ArrayList<CodeTypeBean> getCodeTypeList()
    {
        try
        {
            ArrayList<CodeTypeBean> codeTypeBeanArrayList = new ArrayList<>();
            for (CodeTypeEntity entity : releaseNewpostDao.selectCodeTypeList())
            {
                codeTypeBeanArrayList.add(new CodeTypeBean(entity, 0));
            }
            return codeTypeBeanArrayList;
        }
        catch (DataAccessException e)
        {
            logger.error(e.toString());
            return null;
        }
    }

    @Override
    public ReleaseNewpostType submitRelase(HttpSession session, String title,
                                           String codetype, String tags,
                                           String md, String html)
    {
        /*限制设置*/
        if (session.getAttribute("releaseLimit") != null)
        {
            Date date = (Date) session.getAttribute("releaseLimit");

            Calendar old = Calendar.getInstance();
            old.setTime(date);

            Calendar now = Calendar.getInstance();
            now.setTime(new Date());

            int oldMin = old.get(Calendar.MINUTE);
            int nowMin = now.get(Calendar.MINUTE);

            if (nowMin - oldMin < RELEASELIMIT)
            {
                ReleaseNewpostType releaseNewpostType = ReleaseNewpostType.FAIL_TOMUCH;
                releaseNewpostType.setState("您的发布次数过于频繁，请稍后再试！剩余" +
                        (RELEASELIMIT - (nowMin - oldMin)) + "分钟");
                return releaseNewpostType;
            }
        }

        try
        {
            UserEntity user = (UserEntity) session.getAttribute("user");

            if (user == null)
                return ReleaseNewpostType.FAIL_NOUSER;

            PostEntity postEntity = new PostEntity();

            postEntity.setReleaseUser(user);

            {
                Integer lastId = releaseNewpostDao.selectLastId();
                if (lastId == null)
                {
                    SimpleDateFormat dateFormat = new SimpleDateFormat("YYMMdd");
                    postEntity.setPostId(Integer.valueOf(dateFormat.format(new Date()) + "1"));
                }
                else
                    postEntity.setPostId(lastId + 1);
            }

            postEntity.setTitle(title);
            postEntity.setCodeType(new CodeTypeEntity(codetype));

            /*todo: tags以后使用+连接*/
            {
                String[] tagArray = tags.split("\\+");
                postEntity.setTags(new Gson().toJson(tagArray));
            }

            postEntity.setMd(md);
            postEntity.setHtml(html);

            if (releaseNewpostDao.insertNewPost(postEntity) == 1)
            {
                /*设置发布限制，防止过多刷文*/
                session.setAttribute("releaseLimit", new Date());
                return ReleaseNewpostType.SUCCESS;
            }
            else
                return ReleaseNewpostType.ERROR;
        }
        catch (DataAccessException e)
        {
            logger.error(e.toString());
            return ReleaseNewpostType.ERROR;
        }
    }
}
